<?php
class TDB implements TDB_Interface, TPlugin_Interface, TPlugin_Self_Interface
{
	private static $connection;

	public function etc(){}

	public function getConnection(){
		if(isset(self::$connection)){
			return self::$connection;
		}
		$dsn = $this->getDsn();
		$usr = TDBConf::DB_USER;
		$pas = TDBConf::DB_PASS;
		$opt = array(
			PDO::ATTR_CASE         => PDO::CASE_NATURA,
			PDO::ATTR_ERRMODE      => PDO::ERRMODE_EXCEPTION,
			PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING,
		);
		try{
			self::$connection = new PDO($dsn,$usr,$pas,$opt);
		}catch(PDOException $pex){
			self::$connection = new PDO($dsn,$usr,$pas);
		}
	}

	public function getList(PDOStatement $s){
		$s->execute();
		return $s->fetchAll(PDO::FETCH_OBJ);
	}

	public function bindStr(PDOStatement $s,$n,$i){ $s->bindValue($n,$i,PDO::PARAM_STR); }
	public function bindInt(PDOStatement $s,$n,$i){ $s->bindValue($n,$i,PDO::PARAM_INT); }
	public function execute(PDOStatement $s){ $s->execute(); }
	public function begin(){ self::$connection->beginTransaction(); }
	public function commit(){ self::$connection->commit(); }
	public function rollback(){ self::$connection->rollBack(); }

	private function getDsn(){
		$dsn = "";
		switch(TDBConf::DB_TYPE){
			case 'MySQL':
				$dsn = "mysql";
				break;
			case 'PostgreSQL':
				$dsn = "pgsql";
				break;
			case 'Oracle':
				$dsn = "oci";
				break;
			case 'MSSQL':
				$dsn = "mssql";
				break;
			case 'ODBC':
				$dsn = "odbc";
				break;
			default:
				break;
		}

		$dsn .= ':dbname='.TDBConf::DB_NAME.';host='.TDBConf::DB_HOST.';';
		if(strlen() > 0){
			$dsn .= 'port='.TDBConf::DB_PORT.';';
		}
		return $dsn;
	}
}
